<template>
  <div class="address">
    <Headers :isLeft="true" title="选择收货地址" />
    <div class="city_search">
      <div class="search">
        <span class="city" @click="$router.push('/city')">
          {{city}}
          <i class="fa fa-angle-down"></i>
        </span>
        <i class="fa fa-search"></i>
        <input type="text" v-model="search_val" placeholder="小区/写字楼/学校等" />
      </div>
      <Location :address="address" />
    </div>
    <div class="area">
      <ul class="area_list" v-for="(item,index) in arreaList" :key="index">
        <li @click="selectAddress(item)">
          <h4>{{item.name}}</h4>
          <p>{{item.district}}{{item.address}}</p>
        </li>
      </ul>
    </div>
  </div>
</template>
<script>
import Headers from "./../components/headers.vue";
import Location from "./../components/location.vue";
export default {
  name: "adress",
  data() {
    return {
      city: "",
      search_val: "",
      arreaList: []
    };
  },
  // 不停的监听
  watch: {
    search_val() {
      this.searchPlace();
    }
  },
  methods: {
    selectAddress(item) {
      this.$store.dispatch(
        "setAddress",
        item.district + item.address + item.name
      );
      this.$router.push("/home");
    },
    searchPlace() {
      const self = this;
      // console.log(this.search_val);
      AMap.plugin("AMap.Autocomplete", function() {
        // 实例化Autocomplete
        var autoOptions = {
          //city 限定城市
          city: self.city
        };
        var autoComplete = new AMap.Autocomplete(autoOptions);
        // 注意这里的self.search_val
        autoComplete.search(self.search_val, function(status, result) {
          // 搜索成功时，result即是对应的匹配数据
          console.log(result);
          self.arreaList = result.tips;
        });
      });
    }
  },
  computed: {
    address() {
      return (
        this.$store.getters.location.province +
        " " +
        this.$store.getters.location.city
      );
    }
  },
  components: {
    Headers,
    Location
  },
  // 这里进来刚才city路由传过来的东西
  beforeRouteEnter(to, from, next) {
    // console.log(to);
    next(vm => {
      // 拿到控制台地址的city
      vm.city = to.params.city;
    });
  }
};
</script>
<style scoped>
.search .city {
  padding: 0 10px;
}
.city i {
  margin-right: 10px;
}
.search input {
  margin-left: 5px;
  background-color: #eee;
  outline: none;
  border: none;
}
</style>